import router from './router'
import store from './store'
import { Toast } from 'vant';

import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

// const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar

  // set page title
  document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
    } else {
      const hasGetUserInfo = store.getters.name
      const hasGetCartInfo = store.getters.cartCount
      // console.log( !hasGetCartInfo );
      if(!hasGetCartInfo){
        await store.dispatch('cart/getCart')
      }
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // get user info
          await store.dispatch('user/getInfo')

          next()
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Toast.error({
              message: error || 'Has Error'
          })
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  } else {
    /* has no token*/
    next()
    // if (whiteList.indexOf(to.path) !== -1) {
    //   // in the free login whitelist, go directly
    //   next()
    // } else {
    //   // other pages that do not have permission to access are redirected to the login page.
    //   next(`/login?redirect=${to.path}`)
    // }
  }
})

router.afterEach(() => {
  // finish progress bar
})

// GenerateRoutes({ commit }, data) {
//   return new Promise((resolve, reject) => {
//     getRoute(data).then(res => {
//      // 将获取到的数据进行一个转换，然后存到vuex里
//       const accessedRouters = arrayToMenu(res.data)
//       accessedRouters.concat([{ path: '*', redirect: '/404', hidden: true }])
//       commit('SET_ROUTERS', accessedRouters)
//       resolve()
//     }).catch(error => {
//       reject(error)
//     })
//   })
// }